package com.zj.util.concurrent;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author zhangbo
 * @program: PDF-helper
 * @ClassName AsyncThreadTaskConfig
 * @description:
 * @date 2023-05-27 23:14:44
 */
@Slf4j
@Configuration
public class AsyncKernelThreadPoolConfig implements AsyncConfigurer {

    @Autowired
    private KernelPoolConfig config;


    @Override
    @Bean("threadPoolExecutor")
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setMaxPoolSize(config.getMaxPoolSize());
        executor.setCorePoolSize(config.getCorePoolSize());
        executor.setQueueCapacity(config.getQueueCapacity());
        executor.setThreadNamePrefix(config.getThreadNamePrefix());
        executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(config.getAwaitTerminationSeconds());

        //饱和策略
        executor.setRejectedExecutionHandler(new KernelRejectedExecutionHandler.CallerRunsPolicy());

        //线程初始化
        executor.initialize();
        return executor;
    }


    /**
     * 线程池中针对未捕获的异常处理
     *
     * @return 结果
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
            log.error(ex.getMessage(), ex);
            log.error("exception method:{}", method.getName());
        };
    }
}
